package com.db4o.odbgen.plugins.java.database;

import java.util.ArrayList;
import java.util.List;


import com.db4o.internal.odbgen.StringUtils;
import com.db4o.internal.odbgen.plugins.java.database.DefaulValuetsXmlSchemaElement;
import com.db4o.odbgen.OdbgenException;
import com.db4o.odbgen.TargetLanguage;
import com.db4o.odbgen.plugins.MainGeneratorPlugin;
import com.db4o.odbgen.plugins.Plugin;
import com.db4o.odbgen.plugins.java.maingenerator.MainGenerator;
import com.db4o.odbgen.plugins.java.maingenerator.typedxmlschema.TSClass;
import com.db4o.odbgen.plugins.java.maingenerator.typedxmlschema.TSField;


public class DefaultValue implements Plugin{

	private MainGenerator _mainGenerator;

	/**
	 * See {@link Plugin} for details.
	 */
	@Override
	public List<Class<? extends Plugin>> getPluginDependencies() {
		ArrayList<Class<? extends Plugin>> res = new ArrayList<Class<? extends Plugin>>();
		res.add(MainGenerator.class);
		return res;
	}

	/**
	 * See {@link Plugin} for details.
	 */
	@Override
	public void initialize(MainGeneratorPlugin mainGenerator) {
		this._mainGenerator = (MainGenerator)mainGenerator;
		
	}

	/**
	 * See {@link Plugin} for details.
	 */
	@Override
	public void start() throws OdbgenException {
		for(TSClass tsClass : this._mainGenerator.getTypedXmlSchema().getClasses()){
			for(TSField field : tsClass.getFields()){
				//The field must belong to XmlSchema.
				if(field.getElement()==null) continue
				;
				if(field.getElement().hasSingleChild(DefaulValuetsXmlSchemaElement.DEFAULT.getName())){
					String content = field.getElement().getSingleChild(DefaulValuetsXmlSchemaElement.DEFAULT.getName()).getContent();
					//If the field is a string,  quote the content if necessary.
					if(field.getType().getSimpleName().equals(String.class.getSimpleName())){
						content = StringUtils.addQuotes(content);
					}
					field.setDefaultValue(content);
				}
				
			}
		}
	}


	/**
	 * See {@link Plugin} for details.
	 */
	@Override
	public boolean supportsTargetLanguage(TargetLanguage targetLanguage) {
		if(targetLanguage == TargetLanguage.JAVA){
			return true;
		}
		return false;
	}

}
